package com.alibaba.aliper.server.model.impl;

import java.util.HashMap;
import java.util.Set;

import com.alibaba.aliper.server.model.interfaces.AgentView;
import com.alibaba.aliper.server.model.interfaces.AliperControll;
import com.alibaba.aliper.server.interfaces.AliperRemoteControll;
import com.alibaba.aliper.server.model.interfaces.AliperView;

public class AliperServer implements AliperView ,AliperControll, AliperRemoteControll{
	private AliperServer(){
		
	}
	
	private static AliperServer server = new AliperServer();
	public static AliperServer getAliperServer(){
		return server;
	}
	private HashMap<String,HashMap<String,Agent>> projects = new HashMap<String, HashMap<String,Agent>>();
	@Override
	public AgentView[] getAgents(String project) {
		HashMap<String,Agent> agents = this.projects.get(project);
		if(agents == null)
			return null;
		return agents.values().toArray(new AgentView[agents.size()]);
	}
	
	

	public synchronized Agent getAgentOnCreate(String project,String agentId){
		HashMap<String,Agent> agents = null;
		if(this.projects.containsKey(project)){
			agents = this.projects.get(project);
		} else {
			agents = new HashMap<String, Agent>();
			this.projects.put(project, agents);
		}
		Agent agent = null;
		if(!agents.containsKey(agentId)){
			agent = new Agent(agentId);
			agents.put(agentId, agent);
		} else {
			agent = agents.get(agentId);
		}
		return agent;
	}

	@Override
	public void report(String project,String agentId, String chartId, String lineId,
			long time, double data) {
		this.getAgentOnCreate(project,agentId).getChartOnCreate(chartId).report(lineId,time,data);
	}

	@Override
	public void setRange(String project,String agentId, String chartId, String lineId,
			double min, double max) {
		this.getAgentOnCreate(project,agentId).getChartOnCreate(chartId).getLineOnCreate(lineId).setRange(min,max);
	}



	@Override
	public Agent getAgent(String project,String agentId) {
		HashMap<String,Agent> agents = this.projects.get(project);
		if(agents == null)
			return null;
		return agents.get(agentId);
	}

	@Override
	public synchronized void restart(String project) {
		if(this.projects.containsKey(project)){
			HashMap<String,Agent> p = this.projects.get(project);
			for(Agent agent : p.values()){
				agent.restart();
			}
		}
	}



	@Override
	public synchronized String[] getPojects() {
		Set<String> set = this.projects.keySet();
		return set.toArray(new String[set.size()]);
	}

}
